//
//  MLTextRangeButton.m
//  TycoonSale
//
//  Created by molon on 15/8/2.
//  Copyright (c) 2015年 molon. All rights reserved.
//

#import "MLTextRangeButton.h"
#import <MLKit.h>

#define kBlackOverlayViewDefaultOpacity .35f

#define kWindowLevelMLInputButton UIWindowLevelNormal+1.0f;

#define kDefaultContainerHeight 44.0f
#define kDefaultMargin 5.0f

@class MLTextRangeInputViewController;
@interface MLTextRangeButton()

@property(nonatomic,strong) UIWindow *actionWindow;

- (void)cancelEvent;
- (BOOL)doneWithMin:(NSInteger)min max:(NSInteger)max;

@end

@interface MLTextRangeInputViewController : UIViewController

@property (nonatomic, weak) MLTextRangeButton *inputButton;

@property (nonatomic, strong) UIView *dimmingBlackView;

@property (nonatomic, strong) UIView *containerView;
@property (nonatomic, strong) UITextField *minTextField;
@property (nonatomic, strong) UILabel *separatorLabel;
@property (nonatomic, strong) UITextField *maxTextField;
@property (nonatomic, strong) UIButton *doneButton;

@end

@implementation MLTextRangeInputViewController


- (void)viewDidLoad
{
    [super viewDidLoad];
    
    [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(keyboardWillShow:)
                                                 name:UIKeyboardWillShowNotification
                                               object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(keyboardWillHide:)
                                                 name:UIKeyboardWillHideNotification
                                               object:nil];
    
    //添加黑色覆盖背景
    [self.view addSubview:self.dimmingBlackView];
    //添加输入的容器View
    [self.view addSubview:self.containerView];
    
    //初始的背景颜色
    self.dimmingBlackView.layer.opacity = 0.09f;
    
    
    //直接设置好各个view的位置吧
    self.containerView.frame = CGRectMake(0, self.view.frameBottom-kDefaultContainerHeight, self.view.frameWidth, kDefaultContainerHeight);
    
    self.dimmingBlackView.frame = self.view.bounds;
    
    CGFloat elementHeight = self.containerView.frameHeight-kDefaultMargin*2;
    
#define kDoneButtonWidth 60.0f
    self.doneButton.frame = CGRectMake(self.containerView.frameWidth-kDefaultMargin-kDoneButtonWidth, kDefaultMargin, kDoneButtonWidth, elementHeight);
    
#define kSeparatorLabelWidth 10.0f
    CGFloat textFieldWidth = (self.doneButton.frameX-kDefaultMargin*4-kSeparatorLabelWidth)/2;
    self.maxTextField.frame = CGRectMake(self.doneButton.frameX-kDefaultMargin-textFieldWidth, kDefaultMargin, textFieldWidth, elementHeight);
    self.separatorLabel.frame = CGRectMake(self.maxTextField.frameX-kDefaultMargin-kSeparatorLabelWidth, kDefaultMargin, kSeparatorLabelWidth, elementHeight);
    self.minTextField.frame = CGRectMake(kDefaultMargin, kDefaultMargin, textFieldWidth, elementHeight);
}

- (void)dealloc
{
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}

- (void)viewDidAppear:(BOOL)animated
{
    [super viewDidAppear:animated];
    
    //刚出现的时候，激活
    [self.minTextField becomeFirstResponder];
}

#pragma mark - Keyboard
- (void)keyboardWillShow:(NSNotification *)notification
{
    //推出view
    NSDictionary *userInfo = [notification userInfo];
    CGRect inputViewFrame = [[userInfo objectForKey:UIKeyboardFrameEndUserInfoKey] CGRectValue];
    double duration = [[userInfo objectForKey:UIKeyboardAnimationDurationUserInfoKey]doubleValue];
    
    CGFloat newY = inputViewFrame.origin.y-self.containerView.frameHeight;
//    if (duration==0) {
//        self.containerView.frameY = newY;
//        self.dimmingBlackView.layer.opacity = kBlackOverlayViewDefaultOpacity;
//        return;
//    }
    
    NSInteger inputViewAnimationCurve = [[userInfo objectForKey:UIKeyboardAnimationCurveUserInfoKey] integerValue];
    
    [UIView beginAnimations:nil context:NULL];
    [UIView setAnimationDuration:duration];
    [UIView setAnimationCurve:inputViewAnimationCurve];
    [UIView setAnimationBeginsFromCurrentState:YES];
    
    self.containerView.frameY = newY;
    self.dimmingBlackView.layer.opacity = kBlackOverlayViewDefaultOpacity;
    
    [UIView commitAnimations];
}

- (void)keyboardWillHide:(NSNotification *)notification
{
    NSDictionary *userInfo = [notification userInfo];
    
    [UIView beginAnimations:nil context:NULL];
    [UIView setAnimationDuration:[userInfo[UIKeyboardAnimationDurationUserInfoKey] doubleValue]];
    [UIView setAnimationCurve:[userInfo[UIKeyboardAnimationCurveUserInfoKey] integerValue]];
    [UIView setAnimationBeginsFromCurrentState:YES];
    [UIView setAnimationDelegate:self.inputButton];
    [UIView setAnimationDidStopSelector:@selector(cancelEvent)];
    
    self.dimmingBlackView.layer.opacity = 0.01f;
    self.containerView.frameY = self.view.frameBottom;
    
    [UIView commitAnimations];
}


#pragma mark - getter and setter
- (UIView*)containerView
{
    if (!_containerView) {
        _containerView = [[UIView alloc]init];
        _containerView.backgroundColor = [UIColor whiteColor];
        
        [_containerView addSubview:self.minTextField];
        [_containerView addSubview:self.separatorLabel];
        [_containerView addSubview:self.maxTextField];
        [_containerView addSubview:self.doneButton];
    }
    return _containerView;
}

- (UIButton*)doneButton
{
    if (!_doneButton) {
        _doneButton = [UIButton buttonWithType:UIButtonTypeCustom];
        [_doneButton setTitle:@"确定" forState:UIControlStateNormal];
        _doneButton.titleLabel.font = [UIFont systemFontOfSize:15.0f];
        [_doneButton setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
        [_doneButton addTarget:self action:@selector(done) forControlEvents:UIControlEventTouchUpInside];
    }
    return _doneButton;
}

- (UITextField *)minTextField
{
    if (!_minTextField) {
        _minTextField = [UITextField new];
        _minTextField.font = FONT(14.0f);
        _minTextField.backgroundColor = [UIColor colorWithRed:0.867 green:0.875 blue:0.878 alpha:1.000];
        _minTextField.placeholder = @"最小";
        _minTextField.placeholderColor = [UIColor grayColor];
        _minTextField.keyboardType = UIKeyboardTypeNumberPad;
        _minTextField.textAlignment = NSTextAlignmentCenter;
    }
    return _minTextField;
}

- (UILabel *)separatorLabel
{
    if (!_separatorLabel) {
        UILabel* label = [[UILabel alloc]init];
        label.backgroundColor = [UIColor clearColor];
        label.textColor = [UIColor darkGrayColor];
        label.font = BOLDFONT(18.0f);
        label.textAlignment = NSTextAlignmentCenter;
        label.text = @"-";
        
        _separatorLabel = label;
    }
    return _separatorLabel;
}

- (UITextField *)maxTextField
{
    if (!_maxTextField) {
        _maxTextField = [UITextField new];
        _maxTextField.font = FONT(14.0f);
        _maxTextField.backgroundColor = [UIColor colorWithRed:0.867 green:0.875 blue:0.878 alpha:1.000];
        _maxTextField.placeholder = @"最大";
        _maxTextField.placeholderColor = [UIColor grayColor];
        _maxTextField.keyboardType = UIKeyboardTypeNumberPad;
        _maxTextField.textAlignment = NSTextAlignmentCenter;
    }
    return _maxTextField;
}

- (UIView *)dimmingBlackView
{
    if (!_dimmingBlackView) {
        UIView *blackView = [UIView new];
        blackView.backgroundColor = [UIColor blackColor];
        blackView.userInteractionEnabled = YES;
        blackView.layer.opacity = kBlackOverlayViewDefaultOpacity;
        
        //对其添加点击事件
        UITapGestureRecognizer *tapGesture = [[UITapGestureRecognizer alloc]init];
        tapGesture.numberOfTapsRequired = 1;
        tapGesture.numberOfTouchesRequired = 1;
        [tapGesture addTarget:self action:@selector(tapBlackOverlayViewWithTapGesture:)];
        [blackView addGestureRecognizer:tapGesture];
        
        
        _dimmingBlackView = blackView;

    }
    return _dimmingBlackView;
}

#pragma mark - tap event
- (void)tapBlackOverlayViewWithTapGesture:(UITapGestureRecognizer*)tapGesture
{
    [self.view endEditing:YES];
}

#pragma mark - done event
- (void)done
{
    if ([self.inputButton doneWithMin:[self.minTextField.text integerValue] max:[self.maxTextField.text integerValue]]){
        [self.view endEditing:YES];
    }
}

@end


#pragma mark - button implementation

@implementation MLTextRangeButton

- (id)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    if (self) {
        // Initialization code
        [self setUp];
    }
    return self;
}

- (id)initWithCoder:(NSCoder *)aDecoder
{
    self = [super initWithCoder:aDecoder];
    if (self) {
        [self setUp];
    }
    return self;
}

- (void)setUp
{
    //添加一个点击可成为第一响应者的Target
    [super addTarget:self action:@selector(defaultTarget) forControlEvents:UIControlEventTouchUpInside];
}

//覆盖了，不让用户外部可以添加Target
- (void)addTarget:(id)target action:(SEL)action forControlEvents:(UIControlEvents)controlEvents
{
    return;
}


- (void)defaultTarget
{
    if (!self.actionWindow) {
        MLTextRangeInputViewController *viewController = [[MLTextRangeInputViewController alloc] init];
        viewController.inputButton = self;
        if (self.min>0) {
            viewController.minTextField.text = SIMPLE_INTEGER_STRING(self.min);
        }
        if (self.max>0) {
            viewController.maxTextField.text = SIMPLE_INTEGER_STRING(self.max);
        }
        
        UIWindow *window = [[UIWindow alloc] initWithFrame:[UIScreen mainScreen].bounds];
        window.opaque = NO;
        window.windowLevel = kWindowLevelMLInputButton;
        window.rootViewController = viewController;
        
        self.actionWindow = window;
    }
    [self.actionWindow makeKeyAndVisible];
}


#pragma mark - event
- (void)touchUpInSide
{
    [self defaultTarget];
}

- (void)cancelEvent
{
    self.actionWindow.windowLevel = UIWindowLevelNormal-1;
    [self.actionWindow removeFromSuperview];
    [self.actionWindow resignKeyWindow];
    self.actionWindow = nil;
    
    if (self.didDismissBlock) {
        self.didDismissBlock();
    }
}

- (BOOL)doneWithMin:(NSInteger)min max:(NSInteger)max
{
    if (max<min) {
        SHOW_SIMPLE_TIPS(@"最大值不可小于最小值");
        return NO;
    }
    
    if (min<self.minValue) {
        NSString *tips = [NSString stringWithFormat:@"不可小于%ld",self.minValue];
        SHOW_SIMPLE_TIPS(tips);
        return NO;
    }
    
    if (self.maxValue>0&&max>self.maxValue) {
        NSString *tips = [NSString stringWithFormat:@"不可大于%ld",self.maxValue];
        SHOW_SIMPLE_TIPS(tips);
        return NO;
    }
    
    if (self.didConfirmMinMaxBlock) {
        self.didConfirmMinMaxBlock(min,max);
    }
    
    return YES;
}

@end
